package timing.ukulele.portal.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.portal.view.SysParamVO;
import timing.ukulele.facade.portal.mvc.SysParamControllerFacade;
import timing.ukulele.portal.convertor.ParamConvertor;
import timing.ukulele.portal.dictionary.ParamTypeEnum;
import timing.ukulele.portal.persistent.SysParam;
import timing.ukulele.portal.service.SysParamService;

import java.util.*;

@RestController
public class SysParamController implements SysParamControllerFacade {
    private final SysParamService service;

    public SysParamController(SysParamService service) {
        this.service = service;
    }

    @Override
    public ResponseData<SysParamVO> get(Long id) {
        SysParam po = service.getById(id);
        if (po != null) {
            SysParamVO vo = ParamConvertor.INSTANCE.p2v(po);
            return ResponseData.success(vo);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData<List<SysParamVO>> getParamByParam(Map<String, Object> map) {
        Collection<SysParam> poList = this.service.listByMap(map);
        if (CollectionUtils.isEmpty(poList)) {
            return ResponseData.success();
        }
        List<SysParamVO> voList = new ArrayList<>(poList.size());
        poList.forEach(po -> {
            SysParamVO vo = ParamConvertor.INSTANCE.p2v(po);
            voList.add(vo);
        });
        return ResponseData.success(voList);
    }

    @Override
    public ResponseData<SysParamVO> getParamByKey(String key, Boolean deleted) {
        LambdaQueryChainWrapper<SysParam> query = this.service.lambdaQuery().eq(SysParam::getKey, key);
        if (deleted != null)
            query.eq(SysParam::getDeleted, deleted);
        List<SysParam> list = query.list();
        if (CollectionUtils.isEmpty(list))
            return ResponseData.success();
        SysParam po = list.get(0);
        SysParamVO vo = ParamConvertor.INSTANCE.p2v(po);
        return ResponseData.success(vo);
    }

    @Override
    public ResponseData<Boolean> add(String currentUser, SysParamVO vo) {
        if (vo == null || vo.getId() != null || !StringUtils.hasText(vo.getKey()) || !StringUtils.hasText(vo.getValue()))
            return ResponseData.paramError();
        if (!ParamTypeEnum.hasValue(vo.getType()))
            return ResponseData.paramError( "参数类型错误");
        Long exsits = this.service.lambdaQuery().eq(SysParam::getKey, vo.getKey()).count();
        if (exsits > 0)
            return ResponseData.error(vo.getKey() + "已被使用，请更换");
        SysParam po = ParamConvertor.INSTANCE.v2p(vo);
        this.service.save(po);
        return ResponseData.success();

    }

    @Override
    public ResponseData<Boolean> update(String currentUser, SysParamVO vo) {
        if (vo == null || vo.getId() == null || !StringUtils.hasText(vo.getValue()))
            return ResponseData.paramError();
        if (!ParamTypeEnum.hasValue(vo.getType()))
            return ResponseData.paramError( "参数类型错误");
        SysParam exist = this.service.getById(vo.getId());
        if (exist == null) {
            return ResponseData.error("不存在");
        }
        SysParam po = ParamConvertor.INSTANCE.v2p(vo);
        po.setKey(po.getValue().toUpperCase());
        po.setKey(null);
        if (exist.getType().equals(ParamTypeEnum.SYSTEM.getCode())) {
            po.setType(null);
            // 系统类型参数不允许删除
            if (vo.getDeleted() != null && vo.getDeleted())
                vo.setDeleted(null);
        }
        this.service.updateById(po);
        return ResponseData.success();
    }

    @Override
    public ResponseData<Boolean> delete(String currentUser, Long id) {
        SysParam exist = this.service.getById(id);
        if (exist == null) {
            return ResponseData.error("不存在");
        }
        if (exist.getType().equals(ParamTypeEnum.SYSTEM.getCode())) {
            return ResponseData.error( "系统参数不能删除");
        }
        this.service.lambdaUpdate().set(SysParam::getDeleted, Boolean.TRUE)
                .set(SysParam::getUpdateBy, currentUser)
                .set(SysParam::getUpdateTime, new Date())
                .eq(SysParam::getId, id)
                .update();
        return ResponseData.success();
    }

    @GetMapping("/page/{current}/{size}")
    public ResponseData<IPage<SysParamVO>> getPage(@PathVariable(name = "current") int current,
                                                   @PathVariable(value = "size") int size,
                                                   @RequestParam(value = "key", required = false) String key,
                                                   @RequestParam(value = "value", required = false) String value,
                                                   @RequestParam(value = "remark", required = false) String remark,
                                                   @RequestParam(value = "type", required = false) Integer type,
                                                   @RequestParam(value = "tenantId", required = false) Long tenantId,
                                                   @RequestParam(value = "deleted", required = false) Boolean deleted) {
        if (size == 0) {
            size = 10;
        }
        if (current == 0) {
            current = 1;
        }
        return ResponseData.success(this.service.getPage(type, value, key, remark, tenantId, deleted, current, size));
    }

}
